import { Controller, Inject, Post, Body } from '@midwayjs/decorator';
import { CsrfLow, CsrfMid } from '../interface/user.interface';
import { Context } from '@midwayjs/koa';
import { UserService } from '../service/user.service';

import { UserNotFound, ParamsLack } from '../error/custom.error';
import { checkEssentialParams, md5 } from '../utils';

@Controller('/csrf')
export class CsrfController {
  @Inject()
  ctx: Context;

  @Inject()
  userService: UserService;

  // !!!Csrf 修改密码
  @Post('/low/changePassword')
  async csrfLowChangePassword(@Body() { username, newPassword }: CsrfLow) {
    checkEssentialParams(username, newPassword);
    const target = await this.userService.findUser(username, null, () => {
      throw new UserNotFound();
    });
    await this.userService.changeUser(target, { password: md5(newPassword) });
    return {
      msg: 'Password updated successfully!',
    };
  }

  // !!!Csrf 带token的修改密码
  @Post('/mid/changePassword')
  async csrfMidChangePassword(
    @Body() { username, newPassword, csrfToken }: CsrfMid
  ) {
    checkEssentialParams(username, newPassword, csrfToken);
    // 模拟实现csrf_token
    if (csrfToken !== 'hahahahaha') {
      throw new ParamsLack();
    }
    return await this.csrfLowChangePassword({ username, newPassword });
  }
}
